package com.rp.system.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rp.common.utils.RpUtil;
import com.rp.log.annotation.RpLog;
import com.rp.system.dao.AuthorityDao;
import com.rp.system.dao.ModuleDao;
import com.rp.system.dao.ResourceDao;
import com.rp.system.po.Authority;
import com.rp.system.po.DatasourceConfig;
import com.rp.system.po.Module;
import com.rp.system.po.Resource;

@Service
@Transactional
public class ResourceService {

	@Autowired
	private ResourceDao resourceDao;
	@Autowired
	private AuthorityDao authorityDao;
	@Autowired
	private ModuleDao moduleDao;
	
	/**
	 * 保存资源
	 * @param url
	 * @param name
	 * @param remark
	 * @param moduleId
	 * @param moduleName
	 * @return 
	 */
	@RpLog(desc="保存资源")
	public String saveResource(Resource resource){
		String newId = "";
		resource.setCreateDate(RpUtil.getCurrentDatetime());
		newId = (String) resourceDao.save(resource);
		
		//获取超级管理员权限，将新添加的资源赋给它
		Authority superAuth = authorityDao.getSuperAuthority();
		List<Resource> rescs = new ArrayList<Resource>();
		rescs.add(resource);
		superAuth.getResources().add(resource);
		
		if(resource.getModuleId() != null){
			Module module = moduleDao.get(resource.getModuleId());
			module.setRescNum(module.getRescNum()+1);
			moduleDao.update(module);
		}
		return newId;
	}
	
	/**
	 * 更新资源
	 * @param resource
	 */
	@RpLog(desc="更新资源")
	public void updateResource(Resource resource){
		resource.setUpdateDate(RpUtil.getCurrentDatetime());
		resourceDao.saveOrUpdate(resource);
	}
	
	/**
	 * 删除资源
	 * @param resourceId
	 */
	@RpLog(desc="删除资源")
	public void deleteResource(String resourceId){
		Resource resource = resourceDao.get(resourceId);
		
		if(resource.getModuleId() != null){
			//更新资源所属模块的资源数量
			Module module = moduleDao.get(resource.getModuleId());
			if(module != null){
				module.setRescNum(module.getRescNum()-1);
			}
		}
		
		List<Authority> auths = resource.getAuthorities();
		for (Authority auth : auths) {
			auth.getResources().remove(resource);
		}
		resourceDao.delete(resource);
	}
	
	/**
	 * 导入资源数据
	 * @param dc
	 */
	public void importResource(DatasourceConfig dc){
		DriverManagerDataSource ds = RpUtil.getDriverManagerDataSource(
				dc.getDbType(), dc.getUrl(), dc.getUsername(), dc.getPassword());
		
		JdbcTemplate targetDbJdbcTemplate = new JdbcTemplate();
		targetDbJdbcTemplate.setDataSource(ds);
		
		
	}
	
	
	public ResourceDao getResourceDao() {
		return resourceDao;
	}
	
}
